// 负责和后端进行websocket通信
import 'package:flutter/cupertino.dart';
import 'package:hi_barrage/barrage_model.dart';
import 'package:web_socket_channel/io.dart';

abstract class ISocket {
  // 和服务器连接
  ISocket open(String vid);
  // 发送弹幕
  ISocket send(String message);
  // 关闭连接
  void close();
  // 接收弹幕
  ISocket listen(ValueChanged<List<BarrageModel>> callBack);
}

class HiSocket extends ISocket {
  Map<String, dynamic> headers;
  static const _URL = 'wss://api.devio.org/uapi/fa/barrage/';
  IOWebSocketChannel _channel;
  ValueChanged<List<BarrageModel>> _callBack;
  // 心跳间隔秒数，根据服务器实际timeout时间来调整，这里nginx服务器的timeout为60--
  int _intervalSeconds = 50; //防止超时
  // 构造函数传入 headers--业务层
  HiSocket(this.headers);

  @override
  ISocket open(String vid) {
    _channel = IOWebSocketChannel.connect(_URL + vid,
        headers: headers, pingInterval: Duration(seconds: _intervalSeconds));
    // 发生错误的处理
    _channel.stream.handleError((error) {
      // hyLog('连接发送错误：$error', StackTrace.current);
      print('连接发送错误：$error');
    }).listen((event) {
      _handleMessage(event);
    });
    return this;
  }

  @override
  void close() {
    if (_channel != null) {
      _channel.sink.close();
    }
  }

  @override
  ISocket listen(callBack) {
    _callBack = callBack;
    return this;
  }

  @override
  ISocket send(String message) {
    _channel.sink.add(message);
    return this;
  }

  void _handleMessage(message) {
    // hyLog('received:$message', StackTrace.current);
    var result = BarrageModel.fromJsonString(message);
    if (result != null && _callBack != null) {
      _callBack(result);
    }
  }
}
